package com.ukefu.webim.service.task;

import java.util.Collection;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.ai.AiUtils;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.service.repository.ChatMessageRepository;
import com.ukefu.webim.util.impl.AiMRoundsTimeoutImpl;
import com.ukefu.webim.web.model.AiConfig;
import com.ukefu.webim.web.model.AiUser;

@Configuration
@EnableScheduling
public class XiaoETask {
	
	@Autowired
	private AiMRoundsTimeoutImpl  aiMroundsTimeoutImpl ;
	
	@Autowired
	private ChatMessageRepository chatMessageRes  ;
	
	@Scheduled(fixedDelay= 3000) // 每3秒执行一次 ， 负责检查多轮回复
    public void mrounds() {
		if(UKDataContext.getContext()!=null && UKDataContext.needRunTask()){	//判断系统是否启动完成，避免 未初始化完成即开始执行 任务
			long onlineusers = CacheHelper.getAiUserCacheBean().getSize() ;
			if(onlineusers > 0){
				Collection<?> datas = CacheHelper.getAiUserCacheBean().getAllCacheObject(UKDataContext.SYSTEM_ORGI) ;
				for(Object key : datas){
					AiUser aiUser = (AiUser)CacheHelper.getAiUserCacheBean().getCacheObject(key.toString(), UKDataContext.SYSTEM_ORGI) ;
					if(UKDataContext.model.get("xiaoe")!=null){
						AiConfig aiConfig = AiUtils.initAiConfig(aiUser.getAiid(), aiUser.getOrgi()) ;
						if(aiConfig!=null && aiUser.getLastreplytime() >0 && aiUser.getLastreplytime() < System.currentTimeMillis() && !StringUtils.isBlank(aiUser.getLastmsgid())){
							aiMroundsTimeoutImpl.process(aiUser, chatMessageRes.findById(aiUser.getLastmsgid()), aiUser.getBussid()) ;
						}
					}
				}
			}
		}
	}
}
